﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Jemgine.Engine.Particles
{
    [Category("Draw"), Component]
    public class ParticleEmitter : Jemgine.Engine.EntityComponent, Jemgine.Data.Rotatable, Jemgine.Data.EditorDrawable
    {
        [System.ComponentModel.Editor(typeof(Jemgine.Data.ParticleEffectEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public String Effect { get; set; }
        
        public float EmissionAngle { get; set; }

        public float GetWorldAngle()
        {
            return Me.Angle + EmissionAngle;
        }

        public ParticleEmitter()
        {
            AddInput("Fire", null);
            AddOutput("Relay", null);
        }

        public override void FireTerminal(int InputID, Data.ScriptPayload Payload)
        {
            //Trigger Effect
            var ParticleModule = Sim.GetModule<Particles.ParticleModule>();
            if (ParticleModule != null) ParticleModule.FireEffect(this);
            OutputTerminals[0].Fire(Payload);
        }

        #region Rotatable Members

        object Jemgine.Data.Rotatable.PrepareToRotate()
        {
            return EmissionAngle;
        }

        void Jemgine.Data.Rotatable.ApplyRotation(object Tag, float Rotation)
        {
            float OriginalAngle = (float)Tag;
            EmissionAngle = Jemgine.Math.Angle.Normalize(OriginalAngle + Rotation);
        }

        void Jemgine.Data.Rotatable.Snap(Jemgine.Data.Snapper Snapper)
        {
            EmissionAngle = Jemgine.Math.Angle.Normalize(Snapper.SnapRotation(EmissionAngle));
        }

        #endregion

        #region EditorDrawable Members

        void Jemgine.Data.EditorDrawable.Draw(int ID, Jemgine.Data.EditorDrawData Context, Jemgine.Data.SelectionType Selected)
        {
            base.Draw(ID, Context, Selected);

            if (Selected == Jemgine.Data.SelectionType.Selected || Selected == Jemgine.Data.SelectionType.WorkingSet)
            {
                Context.Renderer.Color = Color.Gold.ToVector4();

                Context.Renderer.DrawLine(Position,
                    Position + Vector2.Transform(new Vector2(0, 2), Matrix.CreateRotationZ(EmissionAngle)),
                    0.2f);
            }
        }

        #endregion
    }
}